package com.ruoyi.app.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteWithdrawalsRecordService;
import com.ruoyi.system.api.domain.base.AccountInfo;
import com.taodaidai.dao.entity.MMaintainerSettlementLog;
import com.taodaidai.dao.entity.MSettlementLog;
import com.tdd.adm.service.feign.IncomeFeignClient;
import com.tdd.wx.users.api.WxUserServiceApi;
import com.tdd.wx.users.entity.WxUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api("收益")
@RestController
@RequestMapping("earn")
@Log4j2
public class EarnController {

    @DubboReference(version = "3.0.0" , interfaceClass = WxUserServiceApi.class, interfaceName = "WxUserService" , lazy = true, check = false)
    private WxUserServiceApi wxUserServiceApi;

//    @DubboReference(version = "1.0.0" , interfaceClass = IncomeServiceApi.class, interfaceName = "IncomeService" , lazy = true, check = false)
//    private IncomeServiceApi incomeServiceApi;

    @Autowired
    IncomeFeignClient incomeFeignClient;
    @Autowired
    private RemoteWithdrawalsRecordService remoteWithdrawalsRecordService;

    @ApiOperation("总收入")
    @GetMapping("totalIncome")
    public R totalIncome() {
        Map rtMap = new HashMap<>();
        String unionId = SecurityUtils.getUnionId();
        WxUser wxUser = wxUserServiceApi.findByUnionId(unionId);
        if (wxUser == null || wxUser.getSysUserId() == null) {
            rtMap.put("total" , "0.00");
        } else {
            try {
                R<AccountInfo> resR = remoteWithdrawalsRecordService.getBalance(unionId, SecurityConstants.INNER);
                if(resR.getData() != null){
                    rtMap.put("total" , resR.getData().getBalance());
                }else {
                    rtMap.put("total" , "0.00");
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                rtMap.put("total" , "0.00");
            }
        }
        return R.ok(rtMap);
    }

    @ApiOperation("服务商收益明细")
    @GetMapping("getMaintainerIncomeLog")
    public R getMaintainerIncomeLog(Integer pageSize, Integer pageNo) {
        if (pageNo == null) {
            pageNo = 0;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        Map rtMap = new HashMap<>();
        String unionId = SecurityUtils.getUnionId();
        WxUser wxUser = wxUserServiceApi.newFindByUnionId(unionId);
        try {
//            List<MSettlementLog> list = incomeServiceApi.getMaintainerIncomeLog(wxUser.getSysUserId(), pageSize, pageNo);
            log.info("调用[incomeFeignClient]服务商收益明细获取的请求参数:{}===>{}===>{},",wxUser.getSysUserId(), pageSize, pageNo);
            log.info("调用[incomeFeignClient]服务商收益明细获取的返回值:{}",new Gson().toJson(incomeFeignClient.getMaintainerIncomeLog(wxUser.getSysUserId(), pageSize, pageNo)));
            List<MSettlementLog> list = getSettleList(incomeFeignClient.getMaintainerIncomeLog(wxUser.getSysUserId(), pageSize, pageNo));
            log.info("调用[incomeFeignClient]服务商收益明细获取的返回值:{}",new Gson().toJson(list));
            rtMap.put("list" , list);
        } catch (Exception e) {
            log.error(e.getMessage());
            List<MMaintainerSettlementLog> list = new ArrayList<>();
//            for (int i = 0; i < 8; i++) {
//                MMaintainerSettlementLog r = new MMaintainerSettlementLog();
//                r.setMainId(wxUser.getSysUserId());
//                r.setMoney(BigDecimal.ONE);
//                r.setRecordTime(LocalDateTime.now());
//                r.setId((i + 1) + "");
//                list.add(r);
//            }
            rtMap.put("list" , list);
        }
        return R.ok(rtMap);
    }

    private List<MSettlementLog> getSettleList(TableDataInfo maintainerIncomeLog) {
        if(maintainerIncomeLog!=null)
        {
            String jsonObject = JSONObject.toJSONString(maintainerIncomeLog.getRows());
            log.info("调用[incomeFeignClient]服务获取的返回值:{}",jsonObject);
            List<MSettlementLog> result = JSONObject.parseObject(jsonObject,new TypeReference<List<MSettlementLog>>(){});
            log.info("fastjson===>转换后的值:{}"+result);
            return result;
        }
        else
        {
            log.info("调用[incomeFeignClient]服务获取的返回值为null");
            return new ArrayList<>(0);
        }
    }


    @ApiOperation("七天收益")
    @GetMapping("get7DayStatic")
    public R get7DayStatic(){
        String unionId = SecurityUtils.getUnionId();
        WxUser wxUser = wxUserServiceApi.newFindByUnionId(unionId);
//        LocalDateTime now = LocalDateTime.now();
//        LocalDateTime begin = now.minusDays(7L);
        String day1 = DateUtil.yesterday().toString("yyyy-MM-dd");
        String day2 = DateUtil.offsetDay(DateTime.now(),-2).toString("yyyy-MM-dd");
        String day3 = DateUtil.offsetDay(DateTime.now(),-3).toString("yyyy-MM-dd");
        String day4 = DateUtil.offsetDay(DateTime.now(),-4).toString("yyyy-MM-dd");
        String day5 = DateUtil.offsetDay(DateTime.now(),-5).toString("yyyy-MM-dd");
        String day6 = DateUtil.offsetDay(DateTime.now(),-6).toString("yyyy-MM-dd");
        String day7 = DateUtil.offsetDay(DateTime.now(),-7).toString("yyyy-MM-dd");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<MSettlementLog> list1 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day1+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day1+" 23:59:59",df))));
        List<MSettlementLog> list2 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day2+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day2+" 23:59:59",df))));
        List<MSettlementLog> list3 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day3+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day3+" 23:59:59",df))));
        List<MSettlementLog> list4 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day4+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day4+" 23:59:59",df))));
        List<MSettlementLog> list5 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day5+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day5+" 23:59:59",df))));
        List<MSettlementLog> list6 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day6+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day6+" 23:59:59",df))));
        List<MSettlementLog> list7 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day7+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day7+" 23:59:59",df))));
        
        BigDecimal money1 = list1.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal money2 = list2.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal money3 = list3.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal money4 = list4.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal money5 = list5.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal money6 = list6.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        BigDecimal money7 = list7.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);

        List<Map> list = new LinkedList();
        Map map1 = new HashMap();
        Map map2 = new HashMap();
        Map map3 = new HashMap();
        Map map4 = new HashMap();
        Map map5 = new HashMap();
        Map map6 = new HashMap();
        Map map7 = new HashMap();

        map1.put(day1,money1);
        map2.put(day2,money2);
        map3.put(day3,money3);
        map4.put(day4,money4);
        map5.put(day5,money5);
        map6.put(day6,money6);
        map7.put(day7,money7);
        list.add(map7);
        list.add(map6);
        list.add(map5);
        list.add(map4);
        list.add(map3);
        list.add(map2);
        list.add(map1);
        log.info("返回给前端的7日收益信息为:{}",new Gson().toJson(list));
        return R.ok(list);
    }

    private long ldtToLong(LocalDateTime dateTime){
        return dateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
    }

    @ApiOperation("昨日收益")
    @GetMapping("yesterDayEarn")
    public R yesterDayEarn(){
        String unionId = SecurityUtils.getUnionId();
        WxUser wxUser = wxUserServiceApi.newFindByUnionId(unionId);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String day1 = DateUtil.yesterday().toString("yyyy-MM-dd");
//        List<MSettlementLog> list1 = incomeServiceApi.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),LocalDateTime.parse(day1+" 00:00:00",df),LocalDateTime.parse(day1+" 23:59:59",df));
        log.info("调用[incomeFeignClient]获取[昨日收益]请求参数:{}==={}==={}",wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day1+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day1+" 23:59:59",df)));
        List<MSettlementLog> list1 = getSettleList(incomeFeignClient.getMaintainerIncomeLogByTime(wxUser.getSysUserId(),ldtToLong(LocalDateTime.parse(day1+" 00:00:00",df)),ldtToLong(LocalDateTime.parse(day1+" 23:59:59",df))));
        log.info("调用[incomeFeignClient]获取[昨日收益]获取的返回数据:{}",new Gson().toJson(list1));
        BigDecimal money1 = list1.stream().map(MSettlementLog::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        log.info("返回给前端的昨日收益:{}",money1);
        return R.ok(money1);
    }

}
